﻿using ControlzEx.Theming;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using sqlmanagewpf.Bussiness;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Xml.Linq;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace sqlmanagewpf
{
    public class Window1ViewModel : BindableBase

    {
        public ObservableCollection<ServerInfo> ServerInfos { get; set; }

        private ObservableCollection<DatabaseInfo> _databaseInfos { get; set; }

        public ObservableCollection<DatabaseInfo> databaseInfos
        {
            get { return _databaseInfos; }
            set
            {
                _databaseInfos = value;
                RaisePropertyChanged(nameof(databaseInfos));
                // Add code here to handle property change notification
            }
        }

        private readonly IEventAggregator _eventAggregator;

        public Window1ViewModel(IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;

            loadxml();
        }

        public ICommand ConnectCommand
        {
            get
            {
                return new DelegateCommand(Connecttodb);
            }
        }

        //IsDatabaseOperationSelected属性
        private bool _isDatabaseOperationSelected;

        public bool IsDatabaseOperationSelected
        {
            get => _isDatabaseOperationSelected;
            set
            {
                _isDatabaseOperationSelected = value;
                RaisePropertyChanged();
            }
        }

        private void Connecttodb()
        {
            //如何跳转到另一个tab
            if (string.IsNullOrEmpty(Server) || string.IsNullOrEmpty(Database)) { return; }

            //
            _eventAggregator.GetEvent<connectEvent>().Publish(new DatabaseConfig()
            {
                Server = Server,
                Database = Database,
                ServerType = ServerType,
                UserName = UserName,
                Password = Password
            });

            IsDatabaseOperationSelected = true;
        }

        private void Connect()
        {
            string strCon = "";
            if (ServerType == "sqlserver")
            {
                //strCon = "Data Source=" + Server + ";Initial Catalog=" + Database + ";User ID=" + UserName + ";Password=" + Password;
                strCon = "Server = " + Server + "; Database = master; Trusted_Connection = True;";
            }
            SqlServerHelper.strConnString = strCon;

            string strSql = "select * from sys.sysdatabases";

            var sqlDataReader = SqlServerHelper.GetReader(strSql);

            databaseInfos = new ObservableCollection<DatabaseInfo>();

            while (sqlDataReader.Read())
            {
                var databaseInfo = new DatabaseInfo
                {
                    Database = sqlDataReader["name"].ToString(),
                    crdate = sqlDataReader["crdate"].ToString()
                };
                this.databaseInfos.Add(databaseInfo);
            }

            databaseInfos.Sort(m => m.Database);
            foreach (var databaseInfo in databaseInfos)
            {
                if (databaseInfo.Database.ToLower() == this.Database.ToLower())
                {
                    SelecteddatabaseInfo = databaseInfo;
                }
            }
        }

        public ICommand SaveCommand
        {
            get
            {
                return new DelegateCommand(save);
            }
        }

        public ICommand DeleteCommand
        {
            get
            {
                return new DelegateCommand(delete);
            }
        }

        private void delete()
        {
            var server = ServerInfos.Where(m => m.Server == Server && m.Database == Database).FirstOrDefault();
            if (server != null)
            {
                this.ServerInfos.Remove(server);
                string json = JsonConvert.SerializeObject(ServerInfos);
                string strPath = Environment.CurrentDirectory + "\\Config" + "\\sql.json";
                File.WriteAllText(strPath, json);
            }
        }

        private string _server;
        private string _serverType = "sqlserver";
        private string _userName;
        private string _password;
        private string _database;

        public string Server
        {
            get => _server;
            set
            {
                _server = value;
                RaisePropertyChanged();
            }
        }

        private ServerInfo _selectedServerInfo;

        public ServerInfo SelectedServerInfo
        {
            get => _selectedServerInfo;
            set
            {
                if (_selectedServerInfo != value)
                {
                    _selectedServerInfo = value;
                    RaisePropertyChanged();
                    OnSelectedServerInfoChanged();
                }
            }
        }

        private DatabaseInfo _SelecteddatabaseInfo;

        public DatabaseInfo SelecteddatabaseInfo
        {
            get => _SelecteddatabaseInfo;
            set
            {
                if (_SelecteddatabaseInfo != value)
                {
                    _SelecteddatabaseInfo = value;
                    RaisePropertyChanged();
                    //OnSelectedServerInfoChanged();
                }
            }
        }

        private void OnSelectedServerInfoChanged()
        {
            // 处理选中事件的逻辑
            // 比如，可以输出选中的服务器信息
            if (_selectedServerInfo != null)
            {
                //Console.WriteLine($"Selected Server: {_selectedServerInfo.Server}");
                Server = _selectedServerInfo.Server;
                ServerType = _selectedServerInfo.ServerType;
                UserName = _selectedServerInfo.UserName;
                Password = _selectedServerInfo.Password;
                Database = _selectedServerInfo.Database;
            }

            Connect();
        }

        public string ServerType
        {
            get => _serverType;
            set
            {
                _serverType = value;
                RaisePropertyChanged();
            }
        }

        public string UserName
        {
            get => _userName;
            set
            {
                _userName = value;
                RaisePropertyChanged();
            }
        }

        public string Password
        {
            get => _password;
            set
            {
                _password = value;
                RaisePropertyChanged();
            }
        }

        public string Database
        {
            get => _database;
            set
            {
                _database = value;
                RaisePropertyChanged();
            }
        }
        public ICommand ChangeLightCommand
        {
            get
            {
                return new DelegateCommand(ChangeLight);
            }
        }
        private void ChangeLight()
        {
            //ThemeManager.Current.ChangeThemeColorScheme(Application.Current, "Light");

            ThemeManager.Current.ChangeTheme(Application.Current, "Light.Blue");

        }

        public ICommand ChangeDarkCommand
        {
            get
            {
                return new DelegateCommand(ChangeDark);
            }
        }
        private void ChangeDark()
        {
            //ThemeManager.Current.ChangeThemeColorScheme(Application.Current, "Dark");
            ThemeManager.Current.ChangeTheme(Application.Current, "Dark.Blue");


        }
        private void save()
        {
            try
            {
                var ServerInfo = new ServerInfo()
                {
                    Database = Database,
                    Id = ServerInfos.Count + 1,
                    Password = Password,
                    Server = Server,
                    ServerType = ServerType,
                    UserName = UserName
                };
                ServerInfos.Add(ServerInfo);
                string json = JsonConvert.SerializeObject(ServerInfos);
                string strPath = Environment.CurrentDirectory + "\\Config" + "\\sql.json";
                File.WriteAllText(strPath, json);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void loadxml()
        {
            ServerInfos = new ObservableCollection<ServerInfo>();
            //this.dataGridView1.Rows.Clear();

            //string result = "";
            //string strPath = Environment.CurrentDirectory + "\\Config" + "\\sql.xml";

            string strPath = Environment.CurrentDirectory + "\\Config" + "\\sql.json";
            string jsonContent = File.ReadAllText(strPath);
            ServerInfos = JsonConvert.DeserializeObject<ObservableCollection<ServerInfo>>(jsonContent);
            SelectedServerInfo = ServerInfos.FirstOrDefault();

            int count = 1;
            foreach (var serverInfo in ServerInfos)
            {
                serverInfo.Id = count++;
            }
        }
    }
}